package com.client;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class Client {

    private String url;  // url为请求的路径

    public Client() {
    }

    /**
     * get请求区块链数据
     * @return
     */
    public HttpResponse doGet(){
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        HttpResponse response = null;
        try {
            response = client.execute(get);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return response;
    }

    /**
     * post交易到RepChain
     * @param json 提交的数据
     * @return
     */
    public HttpResponse doPost(String json){
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        HttpResponse response = null;
        try {
            StringEntity stringEntity = new StringEntity(json);
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(stringEntity);
            response = client.execute(post);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    public Client(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
